package com.boboPlanet.comm.context;

import com.boboPlanet.comm.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;

import java.util.Date;

/**
 * @Description: TODO 业务时间处理
 * @Author: mis_wu
 * @Date: 2023/2/12
 **/
public class BusinessStartTimeContext {

    private static final Logger log = LoggerFactory.getLogger(BusinessStartTimeContext.class);
    public static final String TIME_KEY = "start-time";
    private static final ThreadLocal<String> TIME_CONTEXT = new NamedThreadLocal<>(TIME_KEY);

    public static String getTimeStr(){
        String time = TIME_CONTEXT.get();
        if (StringUtils.isEmpty(time)){
            time = DateUtil.getNowStr();
            log.info("system time not set,will auto fill,time value is:{}",time);
            mock(time);
        }
        return time;
    }

    public static Date getTime(){
        String timeStr = getTimeStr();
        return StringUtils.isNotEmpty(timeStr)?DateUtil.dateStrToDate(timeStr):DateUtil.getNowDate();
    }

    public static void mock(String time){
        if (StringUtils.isNotEmpty(time)){
            log.info("business time is mock,just now...");
            TIME_CONTEXT.set(time);
        }
    }

    public static void clear(){
        TIME_CONTEXT.remove();
    }
}
